import 'package:flutter/material.dart';
import '../utils/responsive_layout.dart';
import '../theme/app_theme.dart';
import 'modern_button.dart';

/**
 * 现代化对话框组件
 * 支持多种样式和动画效果
 */
class ModernDialog extends StatefulWidget {
  final String? title;
  final Widget? titleWidget;
  final String? content;
  final Widget? contentWidget;
  final List<ModernDialogAction>? actions;
  final bool barrierDismissible;
  final EdgeInsetsGeometry? contentPadding;
  final double? maxWidth;
  final double? maxHeight;

  const ModernDialog({
    super.key,
    this.title,
    this.titleWidget,
    this.content,
    this.contentWidget,
    this.actions,
    this.barrierDismissible = true,
    this.contentPadding,
    this.maxWidth,
    this.maxHeight,
  });

  /**
   * 显示对话框
   */
  static Future<T?> show<T>({
    required BuildContext context,
    String? title,
    Widget? titleWidget,
    String? content,
    Widget? contentWidget,
    List<ModernDialogAction>? actions,
    bool barrierDismissible = true,
    EdgeInsetsGeometry? contentPadding,
    double? maxWidth,
    double? maxHeight,
  }) {
    return showDialog<T>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) => ModernDialog(
        title: title,
        titleWidget: titleWidget,
        content: content,
        contentWidget: contentWidget,
        actions: actions,
        barrierDismissible: barrierDismissible,
        contentPadding: contentPadding,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
      ),
    );
  }

  @override
  State<ModernDialog> createState() => _ModernDialogState();
}

class _ModernDialogState extends State<ModernDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _opacityAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _scaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOutBack,
    ));

    _opacityAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOut,
    ));

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);
    final screenSize = MediaQuery.of(context).size;

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _opacityAnimation,
          child: ScaleTransition(
            scale: _scaleAnimation,
            child: Dialog(
              backgroundColor: Colors.transparent,
              elevation: 0,
              child: Container(
                constraints: BoxConstraints(
                  maxWidth: widget.maxWidth ?? (isDesktop ? 400 : screenSize.width * 0.9),
                  maxHeight: widget.maxHeight ?? screenSize.height * 0.8,
                ),
                decoration: BoxDecoration(
                  color: colorScheme.surface,
                  borderRadius: BorderRadius.circular(24),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 20,
                      offset: const Offset(0, 8),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // 标题区域
                    if (widget.title != null || widget.titleWidget != null)
                      _buildTitle(theme, colorScheme, isDesktop),

                    // 内容区域
                    if (widget.content != null || widget.contentWidget != null)
                      _buildContent(theme, colorScheme, isDesktop),

                    // 操作按钮区域
                    if (widget.actions != null && widget.actions!.isNotEmpty)
                      _buildActions(theme, colorScheme, isDesktop),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /**
   * 构建标题区域
   */
  Widget _buildTitle(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Container(
      padding: EdgeInsets.fromLTRB(
        isDesktop ? 24 : 20,
        isDesktop ? 24 : 20,
        isDesktop ? 24 : 20,
        isDesktop ? 16 : 12,
      ),
      child: widget.titleWidget ??
          Text(
            widget.title!,
            style: theme.textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
    );
  }

  /**
   * 构建内容区域
   */
  Widget _buildContent(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Flexible(
      child: Container(
        padding: widget.contentPadding ??
            EdgeInsets.symmetric(
              horizontal: isDesktop ? 24 : 20,
              vertical: isDesktop ? 8 : 4,
            ),
        child: widget.contentWidget ??
            Text(
              widget.content!,
              style: theme.textTheme.bodyLarge?.copyWith(
                color: colorScheme.onSurfaceVariant,
                height: 1.5,
              ),
            ),
      ),
    );
  }

  /**
   * 构建操作按钮区域
   */
  Widget _buildActions(ThemeData theme, ColorScheme colorScheme, bool isDesktop) {
    return Container(
      padding: EdgeInsets.fromLTRB(
        isDesktop ? 24 : 20,
        isDesktop ? 16 : 12,
        isDesktop ? 24 : 20,
        isDesktop ? 24 : 20,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: widget.actions!
            .map((action) => Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: ModernButton(
                    text: action.text,
                    onPressed: action.onPressed,
                    style: action.style,
                    size: isDesktop ? ModernButtonSize.small : ModernButtonSize.medium,
                  ),
                ))
            .toList(),
      ),
    );
  }
}

/**
 * 现代化确认对话框
 */
class ModernConfirmDialog extends StatelessWidget {
  final String title;
  final String content;
  final String confirmText;
  final String cancelText;
  final VoidCallback? onConfirm;
  final VoidCallback? onCancel;
  final bool isDestructive;

  const ModernConfirmDialog({
    super.key,
    required this.title,
    required this.content,
    this.confirmText = '确认',
    this.cancelText = '取消',
    this.onConfirm,
    this.onCancel,
    this.isDestructive = false,
  });

  /**
   * 显示确认对话框
   */
  static Future<bool?> show({
    required BuildContext context,
    required String title,
    required String content,
    String confirmText = '确认',
    String cancelText = '取消',
    bool isDestructive = false,
  }) {
    return ModernDialog.show<bool>(
      context: context,
      title: title,
      content: content,
      actions: [
        ModernDialogAction(
          text: cancelText,
          style: ModernButtonStyle.text,
          onPressed: () => Navigator.of(context).pop(false),
        ),
        ModernDialogAction(
          text: confirmText,
          style: isDestructive ? ModernButtonStyle.filled : ModernButtonStyle.filled,
          onPressed: () => Navigator.of(context).pop(true),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return ModernDialog(
      title: title,
      content: content,
      actions: [
        ModernDialogAction(
          text: cancelText,
          style: ModernButtonStyle.text,
          onPressed: onCancel ?? () => Navigator.of(context).pop(false),
        ),
        ModernDialogAction(
          text: confirmText,
          style: ModernButtonStyle.filled,
          onPressed: onConfirm ?? () => Navigator.of(context).pop(true),
        ),
      ],
    );
  }
}

/**
 * 现代化输入对话框
 */
class ModernInputDialog extends StatefulWidget {
  final String title;
  final String? hint;
  final String? initialValue;
  final String confirmText;
  final String cancelText;
  final ValueChanged<String>? onConfirm;
  final VoidCallback? onCancel;
  final String? Function(String?)? validator;

  const ModernInputDialog({
    super.key,
    required this.title,
    this.hint,
    this.initialValue,
    this.confirmText = '确认',
    this.cancelText = '取消',
    this.onConfirm,
    this.onCancel,
    this.validator,
  });

  /**
   * 显示输入对话框
   */
  static Future<String?> show({
    required BuildContext context,
    required String title,
    String? hint,
    String? initialValue,
    String confirmText = '确认',
    String cancelText = '取消',
    String? Function(String?)? validator,
  }) {
    return showDialog<String>(
      context: context,
      builder: (context) => ModernInputDialog(
        title: title,
        hint: hint,
        initialValue: initialValue,
        confirmText: confirmText,
        cancelText: cancelText,
        validator: validator,
      ),
    );
  }

  @override
  State<ModernInputDialog> createState() => _ModernInputDialogState();
}

class _ModernInputDialogState extends State<ModernInputDialog> {
  late TextEditingController _controller;
  String? _errorText;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialValue);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /**
   * 验证输入
   */
  bool _validateInput() {
    if (widget.validator != null) {
      final error = widget.validator!(_controller.text);
      setState(() {
        _errorText = error;
      });
      return error == null;
    }
    return true;
  }

  /**
   * 确认输入
   */
  void _onConfirm() {
    if (_validateInput()) {
      widget.onConfirm?.call(_controller.text);
      Navigator.of(context).pop(_controller.text);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return ModernDialog(
      title: widget.title,
      contentWidget: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextField(
            controller: _controller,
            autofocus: true,
            decoration: InputDecoration(
              hintText: widget.hint,
              errorText: _errorText,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 12,
              ),
            ),
            onSubmitted: (_) => _onConfirm(),
          ),
        ],
      ),
      actions: [
        ModernDialogAction(
          text: widget.cancelText,
          style: ModernButtonStyle.text,
          onPressed: widget.onCancel ?? () => Navigator.of(context).pop(),
        ),
        ModernDialogAction(
          text: widget.confirmText,
          style: ModernButtonStyle.filled,
          onPressed: _onConfirm,
        ),
      ],
    );
  }
}

/**
 * 对话框操作按钮配置
 */
class ModernDialogAction {
  final String text;
  final VoidCallback? onPressed;
  final ModernButtonStyle style;

  const ModernDialogAction({
    required this.text,
    this.onPressed,
    this.style = ModernButtonStyle.text,
  });
}